
import cloud from '@lafjs/cloud'
import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
const db = cloud.database()
const _ = db.command

export default async function (ctx: FunctionContext) {
  let body = ctx.body
  /**
   * {
   *   "_id":"dsdd",
   *   "pid": "0",//上级部门
   *   "name": "主题",//菜单名称
   *   "type": "ww"//菜单类型
   * }
   */
  if (nw.util.isNull(body._id)){
    return fail("数据不合法")
  }
  //2.构建修改数据
  let updateData  = {updateTime:new Date()}
  if (!nw.util.isNull(body.pid)){
    // @ts-ignore
    updateData.pid = body.pid
  }
  if (!nw.util.isNull(body.name)){
    //2.校验菜单名称是否重复
    let count  = await nw.db.count({
      dbName:"permission",
      whereJson:{
        name:_.eq(body.name),
        deleted:0,
        _id:_.neq(body._id)
      }
    })
    if (count>0){
      return fail("菜单名称重复了")
    }
    // @ts-ignore
    updateData.name = body.name
  }
  if (!nw.util.isNull(body.type)){
    // @ts-ignore
    updateData.type = body.type
  }

  //直接修改即可
  let number = await nw.db.update({
    dbName:"permission",
    dataJson:updateData,
    whereJson:{_id:_.eq(body._id)}
  })
  if (number===0){
    return fail("修改失败")
  }

  return ok("修改成功")



}
